<template>
  <div class="app-container">
    <zl-table ref="table" url="/message/receiveList" :param.sync="par" :default-sort="{prop:'receiveDt',order:'descending'}">
      <template slot="search">
        <el-form :inline="true" :model="par" class="left">
          <el-form-item label="标题">
            <el-input v-model="par.title" clearable placeholder="输入参数名" />
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="par.readStatus" placeholder="请选择" clearable>
              <el-option label="未读" :value="0" />
              <el-option label="已读" :value="1" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button icon="el-icon-search" type="primary" size="small" @click="query">搜 索</el-button>
          </el-form-item>
        </el-form>
      </template>
      <template slot="toolbar">
        <el-row :gutter="10">
          <el-col :span="1.5">
            <el-button size="small" plain type="primary" icon="el-icon-plus" @click="sendMsg">发送消息</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button size="small" plain type="primary" icon="el-icon-check" @click="batchRead">已读</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button size="small" plain type="primary" icon="el-icon-minus" @click="batchUnRead">未读</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button size="small" plain type="danger" icon="el-icon-delete" @click="deleteMsg">删 除</el-button>
          </el-col>
        </el-row>
      </template>
      <template slot="cols">
        <el-table-column align="center" width="50px" type="index" :index="indexMethod" />
        <el-table-column align="center" type="selection" width="50"/>
        <el-table-column align="center" width="40px" prop="attachInfoList">
          <template slot-scope="scope">
            <i v-if="scope.row.attachInfoList!=null && scope.row.attachInfoList.length> 0" class="el-icon-paperclip point main-color"></i>
          </template>
        </el-table-column>
        <el-table-column min-width="150px" prop="title" label="标题" align="left" show-overflow-tooltip sortable="custom"/>
        <el-table-column width="200px" prop="fromName" label="发件人" align="center" show-overflow-tooltip sortable="custom" />
        <el-table-column prop="type" label="消息类型" width="150px" align="center" show-overflow-tooltip sortable="custom">
          <template slot-scope="scope">
            <span>{{ messageTypeMap[scope.row.type] }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="receiveDt" label="接收时间" width="180px" align="center" show-overflow-tooltip sortable="custom"/>
        <el-table-column prop="status" label="状态" align="center" width="120px" show-overflow-tooltip sortable="custom">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.status===1" type="primary">已读</el-tag>
            <el-tag v-else type="danger">未读</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="100px">
          <template slot-scope="scope">
            <el-button
              title="查看"
              type="primary"
              circle
              plain
              class="el-icon-view"
              size="mini"
              @click.native.prevent="readMsg(scope.$index, scope.row)"
            />
          </template>
        </el-table-column>
      </template>
    </zl-table>
    <el-dialog :title="title" :visible.sync="show" destroy-on-close :append-to-body="true" :close-on-click-modal="false" width="800px">
      <el-form ref="editForm" :model="form" :rules="rules" :label-width="labelWidth">
        <el-form-item label="标题" prop="title" class="is-required">
          <el-input v-model="form.title" clearable autocomplete="off" placeholder="请输入" maxlength="200"/>
        </el-form-item>
        <el-form-item label="接收人" prop="receivers" class="is-required" >
          <el-tag
            v-for="(o,i) in fullOrg.receive"
            :key="i"
            :type="orgTypeColorMap[o.orgType]"
            closable
            class="inline-block m5"
            @close="fullOrg.receive.splice(i, 1)"
          >{{ o.orgName }}</el-tag>
          <el-divider v-if="fullOrg.receive.length > 0" direction="vertical" />
          <el-button size="small" icon="el-icon-plus" @click="source=1;fullOrg.showOrgTag = true">选择</el-button>
          <el-button v-show="fullOrg.receive.length > 1" size="small" icon="el-icon-close" @click="fullOrg.receive = []">清空</el-button>
        </el-form-item>
        <el-form-item label="抄送人" prop="duplicates" class="is-required" >
          <el-tag
            v-for="(o,i) in fullOrg.duplicate"
            :key="i"
            :type="orgTypeColorMap[o.orgType]"
            closable
            class="inline-block m5"
            @close="fullOrg.duplicate.splice(i, 1)"
          >{{ o.orgName }}</el-tag>
          <el-divider v-if="fullOrg.duplicate.length > 0" direction="vertical" />
          <el-button size="small" icon="el-icon-plus" @click="source=2;fullOrg.showOrgTag = true">选择</el-button>
          <el-button v-show="fullOrg.duplicate.length > 1" size="small" icon="el-icon-close" @click="fullOrg.duplicate = []">清空</el-button>
        </el-form-item>
        <el-form-item label="内容" prop="content" class="is-required" >
          <div style="max-height: 300px;overflow-y: auto">
            <Editor v-if="show" id="editEditor" ref="editEditor" :value="form.content" :minHeight="150" @on-change="onChange"/>
          </div>
        </el-form-item>
        <el-form-item label="附件" prop="files">
          <Uploader ref="uploader" text="选择文件" v-model="form.files" :limit="5">
          </Uploader>
        </el-form-item>
        <el-form-item label="消息类型" prop="type">
          <el-radio-group v-model="form.type">
            <el-radio :label="0">内部消息</el-radio>
            <el-radio :label="1">邮件</el-radio>
            <el-radio :label="2" disabled="">三方消息</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="消息重要度" prop="level">
          <el-radio-group v-model="form.level">
            <el-radio :label="0">普通</el-radio>
            <el-radio :label="1">紧急</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" :loading="loading" @click="doSend">发 送</el-button>
        <el-button size="small" @click="show = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="选择组织结构"
      :visible.sync="fullOrg.showOrgTag"
      :append-to-body="true"
      :close-on-click-modal="false"
      width="800px"
      destroy-on-close
      @open="openTag"
    >
      <component :is="orgTag" ref="tag" :multi="true" />
      <div slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="addTag">确 定</el-button>
        <el-button size="small" @click="fullOrg.showOrgTag = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>
import { validator } from '@/utils/form'
import ZlTable from '@/components/table/table-con'
import Editor from '@/components/Editor'
import Uploader from '@/components/Uploader/uploader'
import { Mixin } from '@/utils/mixin'
import { deleteReceiveMessage, readMessage, sendMessage, setMessageStatus } from '@/api/message'
export default {
  name: 'Message',
  mixins: [Mixin],
  components: { ZlTable,Editor,Uploader },
  data() {
    return {
      par: {
        title: '',
        readStatus: null
      },
      form: {
        title:'',content:'',level:0,timer:0,type:0,receivers:[],duplicates:[],files:[]
      },
      title: '发送消息',
      loading: false,
      show: false,
      refreshEditor: false,
      source: 1,//1-收件人；2-抄送人
      labelWidth: '120px',
      fullOrg: {
        receive: [],
        duplicate: [],
        showOrgTag: false,
        loading: false
      }
    }
  },
  computed: {
    orgTag() {
      return require('/src/components/tag/full-tag').default
    },
    rules() {
      return {
        title: [
          { validator: validator('notBlank'), message: '标题不能为空', trigger: ['blur', 'change'] }
        ],
        content: [
          { validator: validator(this.checkContent), message: '内容不能为空', trigger: ['blur', 'change'] }
        ],
        receivers: [
          { validator: validator(this.checkReceiver), message: '接收人不能为空', trigger: ['blur', 'change'] }
        ],
        duplicates: [
          { validator: validator(this.checkReceiver), message: '接收人不能为空', trigger: ['blur', 'change'] }
        ]
      }
    }
  },
  mounted() {

  },
  methods: {
    refreshLayout(){
      this.$refs.table.initTableHeight()
    },
    doSend() {
      this.$refs.editForm.validate(r => {
        if (r) {
          console.log(this.form)
          this.loading = true
          sendMessage(this.form).then((r) => {
            this.$message.success('发送成功')
            this.show = false
            this.query()
          }).finally(() => {
            this.loading = false
          })
        }
      })
    },
    checkReceiver() {
      return this.form.receivers.length > 0 || this.form.duplicates.length > 0
    },
    checkContent() {
      return (this.$util.isNotBlank(this.form.content)&& this.form.content!=='<p><br></p>'&& this.form.content!=='<p></p>')
    },
    sendMsg() {
      this.title = '发送消息'
      this.show = true
      this.$nextTick(() => {
        this.form.title = null
        this.form.content = null
        this.form.receivers = []
        this.form.duplicates = []
        this.fullOrg.duplicate = []
        this.fullOrg.receive = []
        this.$refs.uploader.clearFile()
        this.$refs.editForm.clearValidate()
      })
    },
    batchUnRead(index, row) {
      console.log(row)
      const l = this.$refs.table.getSelected()
      if (l.length === 0) {
        this.$message.warning('请选择消息')
        return
      }
      setMessageStatus(0,l.map(o=>o.receiveId)).then((r)=>{
        this.query()
      }).catch((e)=>{
        console.error(e)
        this.$message.error('操作失败')
      })
    },
    deleteMsg(index, row) {
      console.log(row)
      const l = this.$refs.table.getSelected()
      if (l.length === 0) {
        this.$message.warning('请选择消息')
        return
      }
      this.$confirm('确定要删除选中的消息吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'danger'
      }).then(() => {
        deleteReceiveMessage(l.map(o=>o.receiveId)).then((r)=>{
          this.$message.success('删除成功')
          this.query()
        })
      })

    },
    batchRead(index, row) {
      console.log(row)
      const l = this.$refs.table.getSelected()
      if (l.length === 0) {
        this.$message.warning('请选择消息')
        return
      }
      setMessageStatus(1,l.map(o=>o.receiveId)).then((r)=>{
        this.query()
      }).catch((e)=>{
        console.error(e)
        this.$message.error('操作失败')
      })
    },

    readMsg(index, row) {
      console.log(row)
      readMessage(row.receiveId).then((r)=>{
        this.$emit('showMsg',this.$util.copy(row))
        this.query()
      }).catch((e)=>{
        console.error(e)
        this.$message.error('读取消息失败')
      })
    },
    addTag() {
      const p = this.$refs.tag.get()
      if (p.length === 0) {
        this.$message.warning('请选择组织结构')
        return
      }
      // 去重
      const ids = []
      const parent = this.source === 1 ? this.fullOrg.receive : this.fullOrg.duplicate
      for (let i = 0; i < parent.length; i++) {
        ids.push(parent[i].orgId)
      }
      for (let i = 0; i < p.length; i++) {
        if (ids.indexOf(p[i].orgId) === -1) {
          parent.push(p[i])
        }
      }
      this.fullOrg.showOrgTag = false
      if(this.source === 1){
        this.form.receivers = parent.map(o=>o.orgId)
      }else{
        this.form.duplicates = parent.map(o=>o.orgId)
      }
    },
    openTag() {
      this.$nextTick(() => {
        // this.$refs.tag.clear()
        this.$refs.tag.query()
      })
    },
    onChange(o) {
      console.log('onChange')
      this.form.content = o.html
    },
    query() {
      this.$refs.table.query()
    },
    indexMethod(index) {
      return (this.$refs.table.pageNum - 1) * this.$refs.table.pageSize + index + 1
    }
  }
}
</script>
<style scoped>

</style>
